package top.lshaci.learning.bio;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * BIOServer
 *
 * @author lshaci
 * @since 1.0.0
 */
public class BIOServer {

    public static void main(String[] args) throws Exception {
        // 线程池机制
        // 1.创建一个线程池
        // 2.如果有客户端连接，就创建一个线程，与之通信（单独写一个方法）
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);
        System.err.println("服务端启动在6666端口");

        while (true) {
            System.err.println("等待连接...");
            // 监听等待客户端连接
            Socket socket = serverSocket.accept();
            System.err.println("有客户端连接: " + socket.getPort());
            // 创建一个线程
            newCachedThreadPool.execute(() -> handle(socket));
        }
    }

    public static void handle(Socket socket) {
        try (
                InputStream is = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is))
        ) {
            System.err.println("read...");
            String str;
            while ((str = br.readLine()) != null) {
                System.err.println(Thread.currentThread().getName() + " => 接收到的消息：" + str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
